<?php

namespace addons\groupon\listener\order;

use addons\groupon\exception\Exception;
use addons\groupon\model\Cart;
use addons\groupon\model\Config;
use addons\groupon\model\Order;
use addons\groupon\model\OrderItem;
use addons\groupon\model\User;
use addons\groupon\library\traits\StockSale;

/**
 * 订单创建
 */
class Create
{
    use StockSale;


    // 订单创建前
    public function GrouponOrderCreateBefore(&$params) {
        $user = $params['user'];
        $goods_original_amount = $params['goods_original_amount'];
        $goods_amount = $params['goods_amount'];
        $total_amount = $params['total_amount'];
        $total_fee = $params['total_fee'];
        $discount_fee = $params['discount_fee'];
        $coupon_fee = $params['coupon_fee'];
        $new_goods_list = $params['new_goods_list'];
        $user_coupons = $params['user_coupons'];
        $from = $params['from'];

        // 重新获取 user
        $user = User::where('id', $user->id)->find();

        // 限购
        $this->limitBuy($new_goods_list, $user);
    }


    // 订单创建后
    public function GrouponOrderCreateAfter(&$params)
    {
        $user = $params['user'];
        $order = $params['order'];
        $from = $params['from'];
        $new_goods_list = $params['new_goods_list'];

        // 减库存
        $this->realForwardStockSale($order);

        // 删除购物车
        if ($from == 'cart') {
            foreach ($new_goods_list as $delCart) {
                Cart::where([
                    'user_id' => $user->id,
                    'goods_id' => $delCart['goods_id'],
                    'sku_price_id' => $delCart['sku_price_id'],
                ])->delete();
            }
        }

        // 更新订单扩展字段
        $order_ext = $order['ext_arr'];

        // 判断需要支付的金额是否大于 0 
        if ($order['total_fee'] <= 0) {
            // 更新订单扩展字段
            $order->ext = json_encode($order_ext);
            $order->save();

            $order = (new Order)->paymentProcess($order, [
                'order_sn' => $order['order_sn'],
                'transaction_id' => '',
                'notify_time' => date('Y-m-d H:i:s'),
                'buyer_email' => $user->id,
                'payment_json' => json_encode([]),
                'pay_fee' => $order->total_fee,
                'pay_type' => 'wallet'             // 使用 wallet
            ]);
        } else {
            // 添加自动关闭队列
            $config = Config::where('name', 'order')->cache(300)->find();        // 读取配置自动缓存 5 分钟
            $config = isset($config) ? json_decode($config['value'], true) : [];
            
            $close_minue = (isset($config['order_auto_close']) && $config['order_auto_close'] > 0)
                                ? $config['order_auto_close'] : 15; 

            // 更新订单，将过期时间存入订单，前台展示支付倒计时
            $order_ext['expired_time'] = time() + ($close_minue * 60);
            
            \think\Queue::later(($close_minue * 60), '\addons\groupon\job\OrderAutoOper@autoClose', ['order' => $order], 'groupon');
            
            // 更新订单扩展字段
            $order->ext = json_encode($order_ext);
            $order->save();
        }

        return $order;
    }



    /**
     * 判断是否限制购买
     */
    private function limitBuy($new_goods_list, $user) {
        foreach ($new_goods_list as $key => $goods) {
            $detail = $goods['detail'];

            $rules = $detail['limit_rules_arr'];

            if ($detail['activity_status'] == 'ing') {
                // 活动中
                $limit_type = 'activity';
                $limit_num = $rules['limit_time_num'] ?? 0;
            } else {
                $limit_type = $rules['limit_type'] ?? 'all';
                $limit_num = $rules['limit_num'] ?? 0;
            }

            // 不存在，或者 0 不限制
            if ($limit_num <= 0) {
                continue;
            }

            // 查询用户老订单，判断本次下单数量，判断是否超过购买限制, 未支付的或者已完成的都算
            $buy_num = OrderItem::where('user_id', $user['id'])->where('goods_id', $detail['id'])
                ->where(function ($query) use ($limit_type, $detail) {
                    if ($limit_type == 'daily') {
                        // 按天限购
                        $daily_start = strtotime(date('Y-m-d'));
                        $daily_end = strtotime(date('Y-m-d', (time() + 86400))) - 1;
                        $query->where('createtime', 'between', [$daily_start, $daily_end]);
                    } else if ($limit_type == 'activity'){
                        $query->where('createtime', 'between', [$detail['activity_starttime'], $detail['activity_endtime']]);
                    }

                    return $query;
                })
                ->whereExists(function ($query) use ($detail) {
                    $order_table_name = (new Order())->getQuery()->getTable();
                    $table_name = (new OrderItem())->getQuery()->getTable();

                    $query->table($order_table_name)->where('order_id=' . $order_table_name . '.id')
                        ->where('status', '>=', Order::STATUS_NOPAY);       // 未支付，或者已支付的订单都算
                })->sum('goods_num');

            if (($buy_num + $goods['goods_num']) > $limit_num) {
                $msg = '该商品' . ($limit_type == 'daily' ? '每日' : ($limit_type == 'activity' ? '活动期间' : '')) . '限购 ' . $limit_num . ' 件';

                if ($buy_num < $limit_num) {
                    $msg .= '，当前还可购买 ' . ($limit_num - $buy_num) . ' 件';
                }

                new Exception($msg);
            }
        }
    }
}
